<!--
    功能待拆分为更细粒度的minxins，方便功能的组合使用
-->
<template>
	<div class="node-panel grid-panel">
		<div class="node-header">
			<Action-panel v-if="hasAction"
			              v-show="actionShow"
			              :selectStatus="selectStatus"
			              :modalTransfer="actionModalTransfer"
			              :model="listModel.actions"></Action-panel>
			<div v-if="dev">
				<actionCollection></actionCollection>
			</div>
			<Search-input v-if="hasSearch"
			              ref="search"
			              :formRequire="searchRequire"
			              :formCol="searchCol"
			              module='search'
			              :filterData="filterData"
			              :actionModel="searchModel"
			              :fixedSearchPanel="fixedSearchPanel"
			              :data="filterInitData"
			              :fetching="loading"
			              :filterable='true'
			              @formTrigger="filterTrigger"
			              @trigger="filterTrigger"
			              @inputChange="inputChange"
			              :model="listModel"></Search-input>
		</div>
		<Grid-table class="node-content"
		            :unselect="unselect"
		            @rowCheck="$emit('rowCheck',$event)"
		            @dbTrigger="dbTrigger"
		            :singleSelect="singleSelect"
		            @checkChange="checkChange"
		            @actionTrigger="actionTrigger"
		            ref="table"
		            :hasInlineAction="hasInlineAction"
		            :loading="loading"
		            :model="listModel"
		            :hasCheck="hasCheck"
		            :rowCheckMode="rowCheckMode"
		            :keyWord="keyWord"
		            :data="listData">
		</Grid-table>
		<div v-if="hasPage"
		     class="table-page">
			<Page :total="totalCount || listData.length"
			      @on-page-size-change="pageSizeChange"
			      :show-sizer="!(!totalCount && pageSize<listData.length)"
			      :page-size-opts="[20,40,100,200]"
			      :page-size="pageSize"
			      :current="pageOn"
			      show-elevator
			      show-total
			      :size="size"
			      @on-change="fetch"></Page>
		</div>
	</div>
</template>

<script>
import GridTable from '@/components/gridTableFixed';
import SearchInput from '@/components/searchControl';
import Action from 'mixins/action';
import actionCollection from 'action/actionCollection';
import ActionOwner from 'action/owner/index';

import moduleStore from './store';
import $ from '@/common';
import Time from '@/common/time';

var devOpen = 0;
var mixins = [Action];
if ($.dev && devOpen) {
	mixins.push(ActionOwner);
}

export default {
	moduleStore,
	mixins,
	props: {
		hasPage: {
			default: true,
		},
		//不可选中数据文字
		unselect: {
			default: false,
		},
		model: {},
		data: {},
		hasCheck: {
			default: true,
		},
		rowCheckMode: {
			default: false,
		},
		statusData: {},
		hasSearch: {
			default: true,
		},
		hasAction: {
			default: true,
		},
		//允许触发双击事件
		enableDbAction: {
			default: true,
		},
		//初始化完成后自动更新数据
		initFetch: {
			default: true,
		},
		//搜索表单指定列数
		searchCol: {},
		//允许通过data属性改变组件数据
		enableChangeData: {},
		fixedFilter: {},
		singleSelect: {},
		hasInlineAction: {
			default: true,
		},
		//查询额外数据
		extPostData: {},
		actionShow: {
			default: true,
		},
		fixedSearchPanel: {
			default: null,
		},
		size: {},
		//action模态窗口转化位置
		actionModalTransfer: {
			default: true,
		},
	},
	data() {
		return {
			selectStatus: false,
			extRender: {},
			extComponents: {},
			dev: false,
			updateMark: false,
			actionOwner: true,
			keyWord: '',
		};
	},
	computed: {
		searchModel() {
			if (this.listModel && this.listModel.actions) {
				for (let i in this.listModel.actions) {
					if (
						this.listModel.actions[i] &&
						(this.listModel.actions[i].type === 'search' || this.listModel.actions[i].code === 'search')
					) {
						return this.listModel.actions[i];
					}
				}
			}
			return null;
		},
		filterInitData() {
			if (this.statusData && this.statusData.filter) {
				return this.statusData.filter;
			}
		},
		dbAction() {
			if (this.listModel && this.enableDbAction && this.listModel.actions) {
				for (let i in this.listModel.actions) {
					if (
						this.listModel.actions[i] &&
						this.listModel.actions[i].param &&
						this.listModel.actions[i].param.trigger === 'dbclick'
					) {
						return this.listModel.actions[i];
					}
				}
			}
			return null;
		},
		//必填搜索项，有action search.param.require 指定
		searchRequire() {
			var res = null;
			if (this.searchModel && this.searchModel.param && this.searchModel.param.require) {
				res = {};
				let list = this.searchModel.param.require.split(';');
				for (let code of list) {
					res[$.trim(code)] = true;
				}
			}
			return res;
		},
		filterData() {
			return {
				...this.fixedFilter,
			};
		},
		initSearchData() {
			var data = {};
			if (this.model && this.model.fields) {
				for (let i in this.model.fields) {
					let field = this.model.fields[i];
					field.param = field.param || {};
					if (field.param_def_value !== undefined) {
						var value = field.param_def_value;
						if (
							(field.type === 'date' || field.type === 'time' || field.type === 'timestamp') &&
							$.trim(field.param_def_value) === 'now()'
						) {
							var now = new Date();
							value = Time.toTs(`${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} 00:00:00`);
							if (field.param && field.param.range) {
								if (field.type === 'date') {
									data[field.code + '_start'] = value;
									data[field.code + '_end'] = value;
								} else {
									data[field.code + '_start'] = value;
									data[field.code + '_end'] = Time.toTs(
										`${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} 23:59:59`
									);
								}
							} else {
								data[field.code] = value;
							}
						} else {
							data[field.code] = value;
						}
					}
				}
			}
			if (this.fixedFilter) {
				data = $.setObj(data, this.fixedFilter);
			}
			return data;
		},
	},
	watch: {
		fixedFilter(v) {
			this.importFilter(this.fixedFilter);
		},
		extPostData(v) {
			this.setExtPost(v);
		},
		updateMark(v) {
			if (v) {
				this.$emit('updateMark');
				this.updateMark = false;
			}
		},
		loading(v) {
			if (v) {
				this.$emit('update');
			}
		},
		data(v) {
			if (this.enableChangeData) {
				if (v.data) {
					this.setPageData(v);
				} else {
					this.setData(v);
				}
			}
		},
		listData() {
			this.$nextTick(() => {
				this.$emit('updateStatus', {
					data: {
						data: this.listData,
						pageNo: this.pageOn,
						pageSize: this.pageSize,
						totalPageCount: this.pageCount,
						totalCount: this.totalCount,
					},
				});
			});
		},
		model(v) {
			this.setListModel(v);
		},
	},
	methods: {
		inputChange(val) {
			this.$set(this, 'keyWord', val);
		},
		//重绘，条用列表与搜索栏重绘方法
		redraw() {
			this.updateTableStyle();
			if (this.$refs.search) {
				this.$refs.search.redraw();
			}
		},
		//数据过滤查询设置
		filterTrigger(v) {
			this.$emit('updateStatus', { filter: v });
			this.filter(v);
		},
		getSearchFormData() {
			return this.$refs.search.formData();
		},
		setSearchFormData(data) {
			return this.$refs.search.setFormData(data);
		},
		//更新数据
		//双击响应
		dbTrigger(index) {
			if (this.dbAction) {
				this.actionTrigger({
					code: this.dbAction.code,
					row: this.listData[index],
					index,
					data: this.listData[index].id,
				});
			}
			this.$emit('dbTrigger', this.listData[index]);
		},
		update() {
			this.fetch();
		},
		updateTableStyle() {
			this.$refs.table.updateTableStyle();
		},
		checkChange(v) {
			var table = this.$refs.table;
			if (table) {
				for (var i in table.checkList) {
					if (table.checkList[i]) {
						this.selectStatus = true;
						this.$emit('selectStatus', true);
						this.setSelectList(v);
						return;
					}
				}
			}
			this.setSelectList(v);
			this.selectStatus = false;
			this.$emit('selectStatus', false);
		},
		getSelectedIndex() {
			var table = this.$refs.table;
			if (table) {
				return table.getSelectedIndex();
			}
		},
		getSelectedIds() {
			var list = [];
			var table = this.$refs.table;
			if (table) {
				table.checkList.forEach((item, i) => {
					if (item) {
						var row = this.listData[i];
						if (row) {
							list.push(row.id);
						}
					}
				});
			}
			return list;
		},
		getSelectedId() {
			var table = this.$refs.table;
			var value = null;
			if (table) {
				table.checkList.forEach((item, i) => {
					if (item && value === null) {
						var row = this.listData[i];
						if (row) {
							value = row.id;
						}
					}
				});
			}
			return value;
		},
		getSelectedDataRow() {
			var table = this.$refs.table;
			for (var i in table.checkList) {
				if (table.checkList[i]) {
					return this.listData[i];
				}
			}
		},
		//为table组件设置额外组件
		importTableComponents(data) {
			$.setProp(this.$options.components, data);
			this.$refs.table.importTableComponents(data);
		},
		//添加扩展渲染方法
		addExtRender(data) {
			this.extRender = data;
			return this.$refs.table.addExtRender(data);
		},
		setInlineActionStatus(command) {
			this.$refs.table.setInlineActionStatus(command);
		},
	},
	created() {
		this.dev = $.dev && devOpen;
		this.setListModel(this.model);
		if (this.fixedFilter) {
			//临时处理，将固定查询条件注入组件
			this.importFilter(this.fixedFilter);
		}
		//通过编码设置页号缓存
		var code = this.moduleState.bill_code || this.listModel.bill_code || this.listModel.code;
		if (code) {
			var size = $.localPageSize(code);
			if (size) {
				this.setPageSize(size);
			}
		}
		//初始化数据带入
		if (this.data) {
			if (this.data.data) {
				this.setPageData(this.data);
			} else {
				this.setData(this.data);
			}
		}
		if (this.extPostData) {
			this.setExtPost(this.extPostData);
		}
		if (this.initFetch) {
			if (this.statusData && this.statusData.data) {
				this.setPageData(this.statusData.data);
			} else {
				this.filter({
					...this.initSearchData,
					...(this.statusData && this.statusData.filter),
				});
			}
		}
	},
	components: {
		GridTable,
		SearchInput,
		actionCollection,
	},
};
</script>

<style lang="less">
.table-page {
	text-align: right;
	padding-top: 4px;
	padding-bottom: 4px;
	.ivu-select {
		position: relative;
		overflow: visible;
		.ivu-select-dropdown {
			bottom: 38px !important;
			top: auto !important;
		}
	}
	.ivu-page-item-jump-next,
	.ivu-page-item-jump-prev,
	.ivu-page-next,
	.ivu-page-prev,
	.ivu-page-item {
		min-width: 28px;
		height: 28px;
		line-height: 26px;
	}
	.ivu-page-total,
	.ivu-page-options-elevator {
		height: 28px;
		line-height: 28px;
	}
	.ivu-page-options-elevator input {
		height: 28px;
	}
	.ivu-select-single .ivu-select-selection {
		height: 28px;
	}
	.ivu-select-single .ivu-select-selection .ivu-select-placeholder,
	.ivu-select-single .ivu-select-selection .ivu-select-selected-value {
		height: 26px;
		line-height: 26px;
	}
}
.action-right {
	float: right;
}
</style>
